﻿namespace Numbrella.Client.Common
{
	using System.Collections.Generic;
	using System.Collections.ObjectModel;
	using System.Collections.Specialized;
	using System.Diagnostics;
	using System.Threading;
	using System.Windows.Threading;

	public class SimpleMultithreadedObservableCollection<T> : ObservableCollection<T>
	{
		private readonly Dictionary<NotifyCollectionChangedEventHandler, Thread> delegateToThreadMapping =
			new Dictionary<NotifyCollectionChangedEventHandler, Thread>();

		public override event NotifyCollectionChangedEventHandler CollectionChanged
		{
			add
			{
				this.delegateToThreadMapping.Add(value, Thread.CurrentThread);
			}

			remove
			{
				this.delegateToThreadMapping.Remove(value);
			}
		}

		protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
		{
			foreach (KeyValuePair<NotifyCollectionChangedEventHandler, Thread> pair in this.delegateToThreadMapping)
			{
				Dispatcher dispatcher = Dispatcher.FromThread(pair.Value);
				Debug.Assert(dispatcher != null, "Thread dispatcher can not be null there.");
				dispatcher.Invoke(DispatcherPriority.Send, pair.Key, this, e);
			}
		}
	}
}